package com.lp.proto;

import cn.hutool.core.util.HexUtil;
import cn.hutool.json.JSONUtil;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;

import java.util.Arrays;

/**
 * @author lp
 */
public class ProtoTest {

    public static void main(String[] args) {

        //初始化数据
        Message.Data.Builder demo = Message.Data.newBuilder();
        demo.setCode(1)
                .setMessage("消息")
                .setServerName("activity-server")
                .setAsync(true)
                .setData(JSONUtil.toJsonStr("{\"dd\":1}"))
                .build();
        //序列化
        Message.Data build = demo.build();
        //转换成字节数组
        byte[] s = build.toByteArray();
        System.out.println("protobuf数据bytes[]:" + Arrays.toString(s));
        System.out.println("protobuf序列化大小: " + s.length);

        String s1 = HexUtil.encodeHexStr(s);
        System.out.println(s1);

        String jsonObject = null;
        try {
            //反序列化
            Message.Data demo1 = Message.Data.parseFrom(s);
            //转 json
            jsonObject = JsonFormat.printer().print(demo1);

        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }

        System.out.println("Json格式化结果:\n" + jsonObject);
        if (jsonObject != null) {
            System.out.println("Json格式化数据大小: " + jsonObject.getBytes().length);
        }
    }
}
